<#assign ctx= request.contextPath/>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <title>DownUp Service!</title>
    <meta charset="utf-8">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="${ctx}/eureka/css/wro.css">
    <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
</head>
<body id="one">
<#include "header.ftl">
<div class="container-fluid xd-container">
    <#if configErrors ?has_content>
        <#list configErrors as error>
            <h4 id="error"><font size="+1" color="red"><b>${error}</b></font></h4>
        </#list>
    </#if>
    <h1>本地实例信息</h1>
    <table id='service' class="table table-striped table-hover">
        <thead>
        <tr>
            <th>服务名(这个)</th>
            <th>所在服务器</th>
            <th>Jar 包版本</th>
            <th>上一次替换时间</th>
            <th>上传jar包</th>
            <th>状态清除(异常情况下)</th>
            <th>定时任务</th>
            <th>替换服务</th>
            <th>查看Jar历史和任务历史</th>
        </tr>
        </thead>
        <tbody>
        <#if serviceServerMapDtoList ? has_content >
            <#list serviceServerMapDtoList as dto>
                <tr>
                    <td id="serviceName${dto?index}">${dto.serviceName}</td>
                    <#--                    <td>-->
                    <#--                        <#list app.amiCounts as amiCount>-->
                    <#--                            <b>${amiCount.key}</b> (${amiCount.value})<#if amiCount_has_next>,</#if>-->
                    <#--                        </#list>-->
                    <#--                    </td>-->
                    <td id="serverHostList${dto?index}">${dto.serverHostList}</td>
                    <td id="lastRestartTime${dto?index}"><#if dto.jarVersionInfo??>${dto.jarVersionInfo}</#if></td>
                    <td id="lastRestartTime${dto?index}"><#if dto.lastRestartTime??>${dto.lastRestartTime}</#if></td>
                    <td id="uploadJar${dto?index}">
                        <#--                        <a href="${ctx}/service/list"><b>上传</b></a>-->
                        <#--                        <input type="file" id="file_input" multiple>上传 </input>-->
                        <div id="hideBeforeSelectFile${dto?index}" hidden="hidden"></div>
                        <input type="file" class="filebutton${dto?index}" id="fileNo${dto?index}"
                               onchange="fileSelected(${dto?index})"/>
                        <#--                        <input type="file" class="filebutton${dto?index}" id="fileNo${dto?index}" />-->
                        <#--版本信息-->
                        <div id="hideBeforeNewVersion${dto?index}" hidden="hidden"><font color="red">本次上传Jar的版本号（必填，不填默认为文件修改日期）</font>
                            <input type="text" id="newVersion${dto?index}" hidden="hidden"/>
                        </div>
                        <button id="confirmUpload${dto?index}" hidden="hidden" onclick="confirmUpload(${dto?index})">
                            确定上传
                        </button>
                        <div id="uploadResult${dto?index}">上传流信息</div>
                    </td>
                    <#-- 清除异常状态-->
                    <td>
                        <div id="cancelRestartIng">
                            <button id="cancelRestartIng${dto?index}" onclick="cancelRestartIng(${dto?index})">
                                清除服务替换状态
                            </button>
                            <div id="cancelRestartIngResult${dto?index}"></div>
                        </div>
                        <div id="cancelSendJarIng">
                            <button id="cancelSendJarIng${dto?index}" onclick="cancelSendJarIng(${dto?index})">
                                清除Jar包上传状态
                            </button>
                            <div id="cancelSendJarIngResult${dto?index}"></div>
                        </div>
                    </td>
                    <#-- 定时任务 -->
                    <td>
                        <#if dto.schedules ? has_content >
                            <#list dto.schedules as schedule>
                                <div>
                                    <b><#if schedule.taskId??>任务编号: ${schedule.taskId} </#if></b>
                                    <b><#if schedule.scheduleTime??>定时时间: ${schedule.scheduleTime} </#if></b>
                                    <b><#if schedule.jarVersionInfo??>版本信息: ${schedule.jarVersionInfo} </#if></b>
                                    <b><#if schedule.localFilePath??>本地文件路径: ${schedule.localFilePath} </#if></b>
                                    <b><#if schedule.timeToStart??>距离定时时间:${schedule.timeToStart}</#if></b>
                                    <div id="cancelScheduleTask">
                                        <button id="cancelScheduleTask${schedule.taskId}"
                                                onclick="cancelScheduleTask(${schedule.taskId})">
                                            取消定时任务
                                        </button>
                                        <div id="cancelScheduleTaskResult${schedule.taskId}"></div>
                                    </div>
                                </div>
                            </#list>
                        <#else>
                            <div> 无定时任务</div>
                        </#if>
                    </td>
                    <#-- 服务替换-->
                    <td id="restart">
                        <button id="restartRequest${dto?index}" onclick="restartRequest(${dto?index})">开始替换</button>
                        <div id="restartResult${dto?index}">替换流信息</div>
                    </td>
                    <#-- 查看 Jar 历史 和 替换 TaskInfo 信息    -->
                    <td id="check">
                        <a href="${ctx}/localService/getJarsAndTasks?serviceName=${dto.serviceName}">查看Jar历史和任务历史</a>
                    </td>
                </tr>
            </#list>
        <#else>
            <tr>
                <td colspan="4">没有服务实例信息</td>
            </tr>
        </#if>
        </tbody>
    </table>
    <h1>服务器信息</h1>
    <table id='host' class="table table-striped table-hover">
        <thead>
        <tr>
            <th>名称</th>
            <th>IP</th>
            <th>端口</th>
            <th>用户名</th>
        </tr>
        </thead>
        <tbody>
        <#if hosts ? has_content >
            <#list hosts as host>
                <tr>
                    <td id="name${host?index}">${host.name}</td>
                    <td id="host${host?index}">${host.host}</td>
                    <td id="port${host?index}"><#if host.port??>${host.port}</#if></td>
                    <td id="user${host?index}"><#if host.user??>${host.user}</#if></td>
                </tr>
            </#list>
        <#else>
            <tr>
                <td colspan="4">没有服务器列表信息</td>
            </tr>
        </#if>
        </tbody>
    </table>

    <h2>添加本地服务</h2>
    <form method="post" onsubmit="return addService()">
        <p><span>服务名:</span> <input type="text" id="inputServiceName" name="serviceName"></p>
        <p><span>服务器列表(逗号分割):</span> <input type="text" id="inputServerList" name="serverList"></p>
        <button type="submit">添加</button>
    </form>
    <div id="addServiceResult"></div>
    <h2>添加服务器</h2>
    <form method="post" onsubmit="return addHost()">
        <p><span>服务器名:</span> <input type="text" id="inputHostName" name="serviceHostName"></p>
        <p><span>服务器IP:</span> <input type="text" id="inputHostIP" name="serviceHostIP"></p>
        <p><span>服务器端口:</span> <input type="text" id="inputHostPort" name="serviceHostPort"></p>
        <p><span>服务器用户名:</span> <input type="text" id="inputHostUser" name="serviceHostUser"></p>
        <p><span>服务器密码:</span> <input type="text" id="inputHostPassword" name="serviceHostPassword"></p>
        <button type="submit">添加</button>
    </form>
    <div id="addHostResult"></div>
</div>
<script type="text/javascript">

    // 开始服务重启替换接口
    function restartRequest(index) {
        console.log("index" + index);
        $("#restartRequest" + index).attr("disabled", true);
        console.log($("#confirmUpload" + index).parent().siblings()[0].innerText);
        var serviceName = $("#confirmUpload" + index).parent().siblings()[0].innerText;
        $.ajax({
            url: "${ctx}/restart/downUpCluster?serviceName=" + serviceName,
            type: 'get',
            contentType: false,  // 不用任何编码 因为formdata对象自带编码 django能够识别该对象
            processData: false,  // 告诉浏览器不要处理我的数据 直接发就行
            success: function (data) {
                console.log("重启请求收到的 taskid " + data);
                var source = new EventSource('${ctx}/subscribe?taskId=' + data);
                source.onmessage = function (event) {
                    console.log("onmessage" + event.data);
                    text = document.getElementById('restartResult' + index).innerText;
                    // if (text === "bye") {
                    //     document.getElementById('onerror'+index).remove();
                    // } else {
                    text += '\n' + event.data;
                    document.getElementById('restartResult' + index).innerText = text;
                    // }
                };
                source.onerror = function (event) {
                    // document.getElementById('onerror').remove();
                    console.log("source.onerror CLOSED" + event);
                    source.close();
                }
            }
        })
    }


    function fileSelected(index) {
        console.log("调用 了 fileSelected" + index);
        let fileNo = document.querySelector('#fileNo' + index);
        console.log("files " + fileNo.files);
        console.log("files length" + fileNo.files.length);
        console.log("files [0]" + fileNo.files[0]);

        var file = fileNo.files[0];
        console.log("file name :" + file.name);
        var info = document.getElementById('hideBeforeSelectFile' + index);
        console.log("file:" + file);
        var size = file.size / 1024 / 1024;

        info.innerHTML = '文件:' + file.name + '<br>' + '大小:' + size.toFixed(2) + 'M' + '<br>' + '修改:' + file.lastModifiedDate;
        info.removeAttribute("hidden");
        $('#confirmUpload' + index).removeAttr("hidden");
        var version = $('#newVersion' + index);
        version.removeAttr("hidden");
        $('#hideBeforeNewVersion' + index).removeAttr("hidden");
    }


    // 开始上传, 参数为 File 对象
    function confirmUpload(index) {
        var formData = new FormData();
        //设置不能再次点击
        $("#confirmUpload" + index).attr("disabled", true);
        let fileNo = document.querySelector('#fileNo' + index);
        console.log("confirmUpload file " + fileNo.files[0]);
        var file = fileNo.files[0];
        formData.append('file', file); // 'file' 为HTTP Post里的字段名, file 对浏览器里的File对象
        formData.append('serviceName', $("#confirmUpload" + index).parent().siblings()[0].innerText);
        formData.append('serverHostList', $("#confirmUpload" + index).parent().siblings()[1].innerText);
        formData.append('lastRestartTime', $("#confirmUpload" + index).parent().siblings()[3].innerText);

        // 处理 版本信息，如果没有则为日期时分秒，如果有则按照用户填入的
        var version = $("#newVersion" + index);
        var date = file.lastModifiedDate;
        if (version.val() === null || version.val() === '' || typeof version.val() === 'undefined') {
            var dateString = date.toISOString().substr(0, 10).replace(/-/g, '') + date.toTimeString().substr(0, 8).replace(/:/g, '');
            version.val(dateString);
            console.log("version.value 无值：" + version.val());
        } else {
            let versionValue = version.val();
            console.log("index ....versionValue " + versionValue);
            if (versionValue.indexOf("-") >= 0) {
                console.log("index 到这里");
                alert("版本中不能包含 - ");
                throw "版本中不能包含 - ";
            }
            console.log("version.value 有值：" + version.val());
        }
        console.log("va" + version.val());
        formData.append('jarVersionInfo', version.val());
        formData.append('originalFileName', file.name);

        $.ajax({
            url: "${ctx}/uploadJar/uploadJarAndSendToServer",
            type: 'POST',
            data: formData,  // 直接丢对象
            // ajax传文件 一定要指定两个关键性的参数
            contentType: false,  // 不用任何编码 因为formdata对象自带编码 django能够识别该对象
            processData: false,  // 告诉浏览器不要处理我的数据 直接发就行
            success: function (data) {
                console.log("文件上传收到的 taskid " + data);
                var source = new EventSource('${ctx}/subscribe?taskId=' + data);
                source.onmessage = function (event) {
                    console.log("onmessage" + event.data);
                    text = document.getElementById('uploadResult' + index).innerText;
                    // if (text === "bye") {
                    //     document.getElementById('onerror'+index).remove();
                    // } else {
                    text += '\n' + event.data;
                    document.getElementById('uploadResult' + index).innerText = text;
                    // }
                };
                source.onerror = function (event) {
                    // document.getElementById('onerror').remove();
                    console.log("source.onerror CLOSED" + event);
                    source.close();
                }

            }
        })
    }

    function cancelRestartIng(index) {
        $("#cancelRestartIng" + index).attr("disabled", true);
        var serviceName = $("#cancelRestartIng" + index).parent().parent().siblings()[0].innerText;
        console.log("service" + serviceName);
        $.ajax({
            url: "${ctx}/localService/cancelRestartIng?serviceName=" + serviceName,
            type: 'get',
            contentType: false,  // 不用任何编码 因为formdata对象自带编码 django能够识别该对象
            processData: false,  // 告诉浏览器不要处理我的数据 直接发就行
            success: function (data) {
                $("#cancelRestartIng" + index).attr("hidden", "hidden");
                text = document.getElementById('cancelRestartIngResult' + index).innerText;
                text += '\n' + data;
                document.getElementById('cancelRestartIngResult' + index).innerText = text;
            }
        })
    }

    function cancelSendJarIng(index) {
        $("#cancelSendJarIng" + index).attr("disabled", true);
        var serviceName = $("#cancelSendJarIng" + index).parent().parent().siblings()[0].innerText;
        console.log("service" + serviceName);
        $.ajax({
            url: "${ctx}/localService/cancelSendJarIng?serviceName=" + serviceName,
            type: 'get',
            contentType: false,  // 不用任何编码 因为formdata对象自带编码 django能够识别该对象
            processData: false,  // 告诉浏览器不要处理我的数据 直接发就行
            success: function (data) {
                $("#cancelSendJarIng" + index).attr("hidden", "hidden");
                text = document.getElementById('cancelSendJarIngResult' + index).innerText;
                text += '\n' + data;
                document.getElementById('cancelSendJarIngResult' + index).innerText = text;
            }
        })
    }

    <#--<div id="cancelScheduleTask">-->
    <#--    <div id="cancelScheduleTaskResult${schedule.taskId}"></div>-->
    <#--    <button id="cancelScheduleTask${schedule.taskId}"-->
    <#--            onclick="cancelScheduleTask(${schedule.taskId})">-->
    <#--        取消定时任务-->
    <#--    </button>-->
    <#--</div>-->

    function cancelScheduleTask(taskId) {
        $("#cancelScheduleTask" + taskId).attr("disabled", true);
        // var serviceName = $("#cancelScheduleTask" + taskId).parent().parent().siblings()[0].innerText;
        console.log("taskId" + taskId);
        $.ajax({
            url: "${ctx}/schedule/cancelDownUpSchedule?taskId=" + taskId,
            type: 'get',
            contentType: false,  // 不用任何编码 因为formdata对象自带编码 django能够识别该对象
            processData: false,  // 告诉浏览器不要处理我的数据 直接发就行
            success: function (data) {
                $("#cancelDownUpSchedule" + index).attr("hidden", "hidden");
                text = document.getElementById('cancelScheduleTaskResult' + index).innerText;
                text += '\n' + data;
                document.getElementById('cancelScheduleTaskResult' + index).innerText = text;
            }
        })
    }


    function addService() {
        console.log("addService  方法被调用 : ")
        let serviceName = document.getElementById('inputServiceName').value;
        let serverList = document.getElementById('inputServerList').value;
        console.log("serviceName  方法被调用  " + serviceName);
        console.log("serverList  方法被调用  " + serverList);
        var serviceInstance = {
            "serviceName": serviceName,
            "serverList": serverList
        }
        $.ajax({
            url: "${ctx}/localService/add",
            type: 'POST',
            contentType: "application/json", //必须这样写
            dataType: "json",
            processData: false,  // 告诉浏览器不要处理我的数据 直接发就行
            data: JSON.stringify(serviceInstance),
            success: function (data) {
                console.log("addService()  " + data);
                text = document.getElementById('addServiceResult').innerText;
                text += '\n' + event.data;
                document.getElementById('addServiceResult').innerText = text;
            }
        })
        return false;
    }

    function addHost() {
        console.log("addHost  方法被调用 : ")
        let name = document.getElementById('inputHostName').value;
        let host = document.getElementById('inputHostIP').value;
        let port = document.getElementById('inputHostPort').value;
        let user = document.getElementById('inputHostUser').value;
        let password = document.getElementById('inputHostPassword').value;
        var hostInstance = {
            "name": name,
            "host": host,
            "port": port,
            "user": user,
            "password": password
        }
        $.ajax({
            url: "${ctx}/localService/addHost",
            type: 'POST',
            contentType: "application/json", //必须这样写
            dataType: "json",
            processData: false,  // 告诉浏览器不要处理我的数据 直接发就行
            data: JSON.stringify(hostInstance),
            success: function (data) {
                console.log("addHost()  " + data);
                text = document.getElementById('addHostResult').innerText;
                text += '\n' + event.data;
                document.getElementById('addHostResult').innerText = text;
            }
        })
        return false;
    }
</script>
</body>
</html>